package com.lethe.medical.base.filter;

import com.lethe.medical.entity.UserEntity;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 过滤器按照类名首字母的顺序执行
 */
@WebFilter(filterName = "LoginFilter",urlPatterns={"/*"})
public class LoginFilter implements Filter {

    //获取上下文
    private String ctxPath;

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println("LoginFilter执行了");
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        // 请求的url
        String uri = request.getRequestURI();
        //请求的路径中有static，表示静态资源，放过
        if(uri.indexOf("login")>-1){
            chain.doFilter(req, resp);
            return;
        }

        // 获得session
        HttpSession session = request.getSession();
        UserEntity userEntity = (UserEntity)session.getAttribute("userEntity");
        if(userEntity !=null) {
            //已经登录，转发到后台首页
            ServletContext sc = request.getServletContext();

            //暂时放过，会有权限问题
            //sc.getRequestDispatcher("/WEB-INF/jsp/success.jsp");
            chain.doFilter(req, resp);
        }else {
            //没有登录，重定向到登录页面
            //暂时放过，会有权限问题
            response.sendRedirect(request.getContextPath()+"/login.jsp");
        }
    }

    public void init(FilterConfig config) throws ServletException {
        ctxPath = config.getServletContext().getContextPath();
    }

}
